package unimelb.filesync.common.protocol;

import java.util.concurrent.BlockingQueue;

import unimelb.filesync.common.message.FileSyncRequest;
import unimelb.filesync.common.message.NetworkMessage;
import unimelb.filesync.common.misc.ProtocolContext;
import unimelb.filesync.common.network.NetworkConnection;
import unimelb.filesync.common.network.NetworkService;

public class ReadInstructionTask implements Runnable {

    private final NetworkConnection connection;

    private final NetworkService networkService;

    private final BlockingQueue<FileSyncRequest> readMsgQueue;

    public ReadInstructionTask(NetworkConnection connection, ProtocolContext context) {
        super();
        this.connection = connection;
        this.networkService = new NetworkService();
        this.readMsgQueue = context.getObject(ProtocolContext.READ_MSG_QUEUE);
    }

    @Override
    public void run() {
        while (true) {
            final NetworkMessage msg = networkService.readMessage(connection);
            if (msg == null) {
                System.exit(0);
            }
            
            try {
                final FileSyncRequest syncMsg = msg.getContent();
                readMsgQueue.put(syncMsg);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

}
